package com.shk.service.imp;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shk.dao.CheckGroupDao;
import com.shk.entity.PageResult;
import com.shk.entity.QueryPageBean;
import com.shk.entity.Result;
import com.shk.pojo.CheckGroup;
import com.shk.service.CheckGroupService;
import com.shk.service.CheckItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImp implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;
    @Override
    public void add(CheckGroup checkGroup,Integer[] checkitemIds) {
        checkGroupDao.add(checkGroup);
        setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);


    }

    @Override
    public PageResult findPage(Integer currentPage,Integer pageSize,String queryString) {

        PageHelper.startPage(currentPage,pageSize);
        Page<CheckGroup> page = checkGroupDao.findPage(queryString);

        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void deleteById(CheckGroup checkGroup) {
        Integer checkgroup_id = checkGroup.getId();
        checkGroupDao.deleteCheckGroupAndCheckItem(checkgroup_id);
        checkGroupDao.deleteById(checkGroup);

    }

    @Override
    public CheckGroup findById(Integer id) {

        return checkGroupDao.findById(id);
    }

    @Override
    public List<Integer> findByIdSelectCheckItem(Integer id) {
        return checkGroupDao.findByIdSelectCheckItem(id);
    }

    @Override
    public void update(CheckGroup checkGroup,Integer[] checkitemIds) {
        checkGroupDao.update(checkGroup);
       checkGroupDao.deleteCheckGroupAndCheckItem(checkGroup.getId());
       setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);
    }



    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }




    /*设置checkgroup和checkitem之间的关系*/
    public void setCheckGroupAndCheckItem(Integer checkgroupId,Integer[] checkitemIds){
                    /*判断前端传过来的checkitemIds是否为空*/
            if(checkitemIds !=null && checkitemIds.length>0){
                /*遍历checkitemIds*/
                for(Integer checkitemId:checkitemIds){
                    /*创建一个map对象来接收存储 checkgroupId和checkitemId*/
                    Map map = new HashMap();
                    map.put("checkgroup_id",checkgroupId);
                    map.put("checkitem_id",checkitemId);
                    checkGroupDao.setCheckGroupAndCheckItem(map);
                }
            }
        }

}
